package com.maduar.mybatis.demo.controller;

import com.maduar.mybatis.demo.config.AutoConfigProperity;
import com.maduar.mybatis.demo.config.BusinessMessageProductor;
import com.maduar.mybatis.demo.service.UserService;
import com.maduar.mybatis.demo.util.ErrorInfo;
import com.maduar.mybatis.demo.util.Result;
import com.maduar.mybatis.demo.vo.PageResultRet;
import com.maduar.mybatis.demo.vo.UserPageRes;
import com.maduar.mybatis.demo.vo.UserPageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


/**
 * Description:
 *
 * @author maduar maduar@163.com
 * @date 2021-04-03 16:44
 */
@Controller
@RequestMapping("/demo")
public class MybatisController {

    public static Logger logger = LoggerFactory.getLogger(MybatisController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private BusinessMessageProductor sender;

    @Autowired
    private AutoConfigProperity autoConfigProperity;

    @GetMapping("hello")
    public ResponseEntity<String> getHello(@RequestParam(name = "str", required = false, defaultValue = "") String str) {
        if (StringUtils.isEmpty(str)) {
            return ResponseEntity.badRequest().body("error");
        }
        return new ResponseEntity<>("Hello World!" + autoConfigProperity.getTest(), HttpStatus.OK);
    }

    @PostMapping("/listUser")
    public ResponseEntity<Result<PageResultRet<UserPageRes>>> listUser(@RequestBody UserPageVo pageVo) {

        try {

            PageResultRet<UserPageRes> res = userService.listPageUser(pageVo);
            return ResponseEntity.ok(Result.success(res));
        } catch (Exception e) {
            logger.error("/demo/listUser: PageVo: {}, e: {}", pageVo, e);
            return ResponseEntity.ok(Result.error(ErrorInfo.serviceError(e.getMessage())));
        }

//        return new ResponseEntity<IPage<UserPageVo>>(res, HttpStatus.OK);
    }

    @GetMapping("/oprater")
    public ResponseEntity<Integer> operate(Integer a, Integer b, Integer oprate) {
        return new ResponseEntity<>(userService.exec(a, b, oprate), HttpStatus.OK);
    }

    @RequestMapping("sendmsg")
    public ResponseEntity<Integer> sendMsg(String msg) {
        sender.sendMsg(msg);
        return new ResponseEntity<>(0, HttpStatus.OK);
    }
}
